package fr.hoteia.appengine.archetype.server.service.util;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.springframework.mail.javamail.MimeMessagePreparator;

/**
 * <p>
 * <a href="MimeMessagePreparatorImpl.java.html"><i>View Source</i></a>
 * </p>
 *
 * @author Denis GOSSET <a href="http://www.hoteia.com"><i>Hoteia.com</i></a>
 * 
 */
public class MimeMessagePreparatorImpl implements MimeMessagePreparator {

	private InternetAddress from;
	private InternetAddress to;
	private InternetAddress cc;
	private InternetAddress replyTo;
	private String subject;
	private String plainTextContent;
	private String htmlContent;

	public InternetAddress getFrom() {
		return this.from;
	}
	
	public void setFrom(InternetAddress from) {
		this.from = from;
	}
	
	public InternetAddress getTo() {
		return this.to;
	}
	
	public void setTo(InternetAddress to) {
		this.to = to;
	}
	
	public InternetAddress getCc() {
		return this.cc;
	}
	
	public void setCc(InternetAddress cc) {
		this.cc = cc;
	}

	public InternetAddress getReplyTo() {
		return this.replyTo;
	}
	
	public void setReplyTo(InternetAddress replyTo) {
		this.replyTo = replyTo;
	}
	
	public String getSubject() {
		return this.subject;
	}
	
	public void setSubject(String subject) {
		this.subject = subject;
	}
	
	public String getPlainTextContent() {
		return this.plainTextContent;
	}
	
	public void setPlainTextContent(String plainTextContent) {
		this.plainTextContent = plainTextContent;
	}
	
	public String getHtmlContent() {
		return this.htmlContent;
	}
	
	public void setHtmlContent(String htmlContent) {
		this.htmlContent = htmlContent;
	}
	
	public void prepare(MimeMessage message) throws Exception {
	
		if( getFrom() != null )
			message.setFrom(getFrom());
		if( getTo() != null )
			message.addRecipients(Message.RecipientType.TO, getTo().toString());
		if( getCc() != null )
			message.addRecipients(Message.RecipientType.CC, getCc().toString());
		if( getSubject() != null )
			message.setSubject(getSubject());
		
		MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
		message.setContent(mimeMultipart);
				
		if( getPlainTextContent() != null ){
			BodyPart textBodyPart = new MimeBodyPart();
			textBodyPart.setContent(getPlainTextContent(), "text/plain");
			mimeMultipart.addBodyPart(textBodyPart);
		}
		
		if( getHtmlContent() != null ){
			BodyPart htmlBodyPart = new MimeBodyPart();
			htmlBodyPart.setContent(getHtmlContent(), "text/html");
			mimeMultipart.addBodyPart(htmlBodyPart);
		}

	}
}
